<template>
  <div class="container" :style="`height:${view.height}px;`">
    <!-- <el-button type="primary" class="mb-20" @click="exportAllData">导出所有表为 JSON</el-button> -->
    <el-row >
      <el-col  :span="24" style="display: flex;justify-content: space-between;margin-bottom: 20px;">
        <div>
          <h1>设计成果表</h1>
        </div>
        <el-button type="primary" class="mb-20" @click="exportToExcel">导出所有表为EXCEL</el-button>
      </el-col>
    </el-row>
    <!-- 设计参数 -->
    <el-card shadow="hover" class="mb-20">
      <div slot="header" class="clearfix">
        <span>设计参数</span>
      </div>
      <el-row :gutter="10">
        <el-col :span="6" v-for="(value, key) in designParams" :key="key">
          <p><b>{{ key }}</b>：{{ value }}</p>
        </el-col>
      </el-row>
    </el-card>
    <!-- 设计洪水成果表 -->
    <el-card shadow="hover" v-if="props.showResultTable"   class="mb-20">
      <div slot="header" class="clearfix">
        <span>设计洪水成果表</span>
      </div>
      <el-table size="small" :data="floodData" :border="true" style="width: 100%">
        <el-table-column prop="frequency" label="频率 (%)" :align="'center'" />
        <el-table-column prop="peak_flow" label="Qm (m³/s)" :align="'center'" />
        <el-table-column prop="tau" label="τ (h)" :align="'center'" />
        <el-table-column prop="psi" label="ψ" :align="'center'" />
        <el-table-column prop="n" label="n" :align="'center'" />
      </el-table>
    </el-card>
    <!-- 设计暴雨成果表 -->
    <el-card shadow="hover" class="mb-20">
      <div slot="header" class="clearfix">
        <span>设计暴雨成果表</span>
      </div>
      <el-table size="small" :data="rainfallData" :border="true" style="width: 100%">
        <el-table-column prop="item" label="项目" :align="'center'" />
        <el-table-column v-for="duration in durations" :key="duration" :prop="duration" :label="duration"
          :align="'center'" />
      </el-table>
    </el-card>

    <!-- 设计净雨成果表 -->
    <el-card shadow="hover" class="mb-20">
      <div slot="header" class="clearfix">
        <span>设计净雨成果表</span>
      </div>
      <el-table size="small" :data="netRainfallData" :border="true" style="width: 100%">
        <el-table-column prop="frequency" label="频率 (%)" :align="'center'" />
        <el-table-column prop="p" label="P (mm)" :align="'center'" />
        <el-table-column prop="pa" label="Pa (mm)" :align="'center'" />
        <el-table-column prop="p_plus_pa" label="P + Pa (mm)" :align="'center'" />
        <el-table-column prop="r" label="R (mm)" :align="'center'" />
      </el-table>
    </el-card>

    <!-- 设计净雨(概化)时程分配 -->
    <el-card shadow="hover" class="mb-20">
      <div slot="header" class="clearfix">
        <span>设计净雨(概化)时程分配</span>
      </div>
      <el-table size="small" :data="rainfallAllocationData" :border="true" style="width: 100%">
        <el-table-column prop="time" label="时程" :align="'center'" />
        <el-table-column v-for="frequency in frequencies" :key="frequency" :prop="frequency" :label="frequency"
          :align="'center'" />
      </el-table>
    </el-card>


  </div>
</template>

<script setup lang="ts">
import { ref, watch, reactive } from "vue";
import * as XLSX from "xlsx";
// 初始化数据
const props = defineProps<{
  resultsData: any,
  showResultTable: Boolean
}>();
const emits = defineEmits(['calcSubmitHandler']);
// 导出所有表格数据为 JSON 文件
const exportAllData = () => {
  const allData = {
    designParams: designParams.value,
    rainfallData: rainfallData.value,
    netRainfallData: netRainfallData.value,
    rainfallAllocationData: rainfallAllocationData.value,
    floodData: floodData.value,
  };

  const jsonData = JSON.stringify(allData, null, 2); // 格式化 JSON 数据
  emits('calcSubmitHandler', jsonData)
  
};

// 导出所有表格数据为 Excel 文件
const exportToExcel = () => {
  const workbook = XLSX.utils.book_new();

  const addSheet = (data, sheetName) => {
    const worksheet = XLSX.utils.json_to_sheet(data);
    XLSX.utils.book_append_sheet(workbook, worksheet, sheetName);
  };

  addSheet([designParams.value], "设计参数");
  addSheet(rainfallData.value, "设计暴雨成果表");
  addSheet(netRainfallData.value, "设计净雨成果表");
  addSheet(rainfallAllocationData.value, "设计净雨(概化)时程分配");
  addSheet(floodData.value, "设计洪水成果表");

  XLSX.writeFile(workbook, "results.xlsx");
};



// 设计参数
const designParams = ref({});
watch(
  () => props.resultsData,
  (newVal) => {
    const session = newVal.session;
    designParams.value = {
      经度: session.lon.toFixed(6),
      纬度: session.lat.toFixed(6),
      水文分区: newVal.area_name,
      流域面积F: session.f.toFixed(3),
      干流长度L: session.l.toFixed(3),
      平均比降J: session.j.toFixed(4),
      θ: session.theta.toFixed(2),
      汇流参数m: session.m.toFixed(3),
      最大初损Imax: session.imax.toFixed(2),
      平均入渗率μ: session.mu.toFixed(2),
    };
  },
  { immediate: true }
);

// 表格数据
const durations = ["10分钟", "1小时", "6小时", "24小时"];
const rainfallData = ref([]);
watch(
  () => props.resultsData,
  (newVal) => {
    const session = newVal.session;
    rainfallData.value = ["Cv", "Cs", "点雨量均值(mm)", "点面系数"].map(
      (item, index) => {
        const dataKey = ["cvs", "css", "yls", "alphas"][index];
        return {
          item,
          ...Object.fromEntries(
            durations.map((_, i) => [
              durations[i],
              session[dataKey][i]?.toFixed(2) || "-",
            ])
          ),
        };
      }
    );

    setTimeout(() => {
      exportAllData()
    }, 0)
  },
  { immediate: true }
);

const netRainfallData = ref([]);
watch(
  () => props.resultsData,
  (newVal) => {
    netRainfallData.value = newVal.session.ps.map((ps, index) => ({
      frequency: `${(ps * 100).toFixed(2)}%`,
      p: newVal.design_area_rainfalls[index][3].toFixed(2),
      pa: newVal.pas[index].toFixed(2),
      p_plus_pa: (
        newVal.design_area_rainfalls[index][3] + newVal.pas[index]
      ).toFixed(2),
      r: newVal.r24ps[index].toFixed(2),
    }));
  },
  { immediate: true }
);

const frequencies = ref([]);
const rainfallAllocationData = ref([]);
watch(
  () => props.resultsData,
  (newVal) => {
    frequencies.value = newVal.session.ps.map(
      (ps) => `${(ps * 100).toFixed(2)}%`
    );
    rainfallAllocationData.value = newVal.r_24h_allocate[0].map(
      (_, timeIndex) => {
        const row = { time: `${timeIndex + 1}时` };
        newVal.r_24h_allocate.forEach((frequencyData, freqIndex) => {
          row[frequencies.value[freqIndex]] =
            frequencyData[timeIndex]?.toFixed(2) || "-";
        });
        return row;
      }
    );
  },
  { immediate: true }
);

const floodData = ref([]);
watch(
  () => props.resultsData,
  (newVal) => {
    floodData.value = newVal.session.ps.map((ps, index) => {
      const qs = newVal.qs[index] || [0, 0, 0, 0];
      return {
        frequency: `${(ps * 100).toFixed(2)}%`,
        peak_flow: qs[0]?.toFixed(2) || "-",
        tau: qs[1]?.toFixed(2) || "-",
        psi: qs[2]?.toFixed(2) || "-",
        n: qs[3]?.toFixed(2) || "-",
      };
    });
  },
  { immediate: true }
);

const view = reactive({
  height: window.innerHeight - 750,
});
</script>
<style>
.container {
  overflow: auto;
}
</style>